
capture log close
log using $log/AED_dataprep_10_outcomes_reg, text replace

clear
set mem 5000m
set matsize 800
set more off

set trace off
   
/* ------------------------------------------------- */
/* --- Merge with regional outcome variables ------- */
/* ------------------------------------------------- */



foreach iebversion in v901 {


forvalue year = 2001/2004 {
	
	use $data/eintritte_ue_`year'_`iebversion', clear
	
	
	local yearafter = `year'+2
	local what "`year'/`yearafter'"
		
			
	forvalue jahr = `what' {
	
	
	joinby iza_id using $data/outcome_reg_monthly_y`jahr'_v901.dta, unmatched(master)
	tab _merge
	drop _merge
	
	}
	
	keep iza_id iza_wo_aa_* iza_id iza_wo_kreis_* iza_ao_aa_* 
	
	reshape long iza_wo_kreis_ iza_wo_aa_ iza_ao_aa_ , i(iza_id) j(lfd)
		
	
	tempfile location_`year'
	save `location_`year'', replace
	
	
	use $data/entries_outcome_`year'_`iebversion',clear
	
	capture drop iza_ao_* iza_wo_* 
	
	joinby iza_id lfd using `location_`year'',unmatched(master)
	tab _merge
	drop _merge
	
	/*Drop individuals with more than 2/3 of missing information in place of residence*/
	sort iza_id lfd
	by iza_id: gen t=_n
	
	destring iza_wo_kreis_ iza_wo_aa_ iza_ao_aa_ ,replace
	replace iza_wo_kreis_=. if iza_wo_kreis_<1000
	replace iza_wo_kreis_=. if iza_wo_kreis==.z
	
	gen indicator_wo=1 if iza_wo_kreis_~=.
	by iza_id: egen wo_nonmis=sum(indicator_wo)
	drop if wo_nonmis<16
	drop indicator_wo
	
	*Place of residence during the first 3 months after entry into unemployment
	foreach type in kreis aa {
	gen iza_wo_`type'_eintr0=iza_wo_`type'_ if t==1
	replace iza_wo_`type'_eintr0=iza_wo_`type'_ if t==2 &iza_wo_`type'_[_n-1]==.
	replace iza_wo_`type'_eintr0=iza_wo_`type'_ if t==3 & iza_wo_`type'_[_n-1]==. & iza_wo_`type'_[_n-2]==.
	by iza_id: egen iza_wo_`type'_eintr=max(iza_wo_`type'_eintr0)
	drop iza_wo_`type'_eintr0
	replace iza_wo_`type'_=iza_wo_`type'_eintr if t==1
	}
	
	*Drop individuals with missing place of residence
	drop if iza_wo_kreis_eintr==.
	
	foreach type in kreis aa {
	replace iza_wo_`type'_=iza_wo_`type'_[_n-1] if iza_wo_`type'_==. & iza_wo_`type'_[_n-1]==iza_wo_`type'_[_n+1] & iza_wo_`type'_[_n-1]~=.
	}
	
	gen ind_missing_wo0=1 if iza_wo_kreis_==.
	by iza_id: egen ind_missing_wo=max(ind_missing_wo0)
	drop ind_missing_wo0
	
	replace iza_wo_kreis_=iza_wo_kreis_[_n-1] if iza_wo_kreis_==.
	replace iza_wo_aa_=iza_wo_aa_[_n-1] if iza_wo_aa_==.
	
	
	save $data/entries_outcome_`year'_`iebversion',replace
	}
	
	}
	
log close


